import Vue from 'vue';
import Store from 'src/store';
import {userMessage} from "src/lib/util/message";
import {i18n} from "boot/i18n";

const Account = {
  login: async (username, password) => {
    let {data} = await Vue.prototype.$axios.post(`api/account/login`, { username, password });
    if (data.result) {
      Store.commit('account/update', data.data);
      return true;
    } else {
      userMessage('error', i18n.t(data.error) || '发生了一些错误，请稍后再试。');
    }
    return false;
  },
  update: async (payload) => {
    let {data} = await Vue.prototype.$axios.post(`api/account/update`, {
      username: Store.state.account.username,
      token: Store.state.account.token,
      ...payload
    });
    if (data.result) {
      Store.commit('account/update', data.data);
      return true;
    } else {
      userMessage('error', i18n.t(data.error) || '发生了一些错误，请稍后再试。');
      if (data.error === 'ERR_TOKEN_INVALID' || data.error === 'ERR_TOKEN_EXCEEDED') {
        Store.commit('account/remove');
        window.location.href = "/account";
      }
    }
    return false;
  }
}

export default Account;
